package com.ruoyi.project.system.controller;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.BeiDiaoBase;
import com.ruoyi.project.system.domain.SiyuCharge;
import com.ruoyi.project.system.domain.dto.BeiDiaoDto;
import com.ruoyi.project.system.domain.dto.BeiDiaoReportBody;
import com.ruoyi.project.system.domain.dto.FacialVerification;
import com.ruoyi.project.system.domain.dto.FeeResult;
import com.ruoyi.project.system.domain.vo.*;
import com.ruoyi.project.system.mapper.SiyuChargeMapper;
import com.ruoyi.project.system.mapper.SiyuProductMapper;
import com.ruoyi.project.system.mapper.TzBeiDiaoMapper;
import com.ruoyi.project.system.service.ISiyuQueryService;
import com.ruoyi.project.system.service.TencentService;
import com.ruoyi.project.system.service.TzBeiDiaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.util.List;

import static com.ruoyi.common.utils.uuid.Seq.getId;

@RestController
@RequestMapping("/system/beiDiao")
public class TzBeiDiaoController extends BaseController {

    @Autowired
    private TzBeiDiaoService tbds;

    @Autowired
    private ISiyuQueryService isqs;

    @Autowired
    private TencentService tencentService;

    @Autowired
    private TzBeiDiaoMapper tbdm;

    @Autowired
    private SiyuProductMapper spm;

    @Autowired
    private SiyuChargeMapper scm;

    @GetMapping("/lookAuthImg")
    public AjaxResult lookAuthImg(@NotBlank String orderNo) {
        return success(tbdm.photo(orderNo));
    }

    @GetMapping("/product")
    public AjaxResult product() {
        Long userId = SecurityUtils.getUserId();
        List<ProductEnable> productEnables = spm.selectEnableList(userId, 4);
        if (productEnables == null || productEnables.isEmpty()) {
            warn("暂无可用产品");
        }
        List<ProductPriceVo> ppv = tbds.beiDiaoProduct(productEnables, userId);
        return success(ppv);
    }

    @GetMapping("/list")
    public TableDataInfo list(BeiDiaoSearch bds) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        if (!SecurityUtils.isAdmin(userId)) {
            bds.setUserId(userId);
        }
        List<BeiDiaoVo> list = tbdm.selectBeiDiaoList(bds);
        for (BeiDiaoVo bdv : list) {
            String method = bdv.getAuthMethod();
            if ("elec".equals(method)) {
                bdv.setAuthMethod("线上人脸授权");

            } else if ("offline".equals(method)) {
                bdv.setAuthMethod("线下签署授权");
            }
        }
        return getDataTable(list);
    }

    @RepeatSubmit
    @Transactional
    @PostMapping("/offlineAuth")
    public AjaxResult offlineAuthAdd(@RequestBody BeiDiaoDto beiDiaoDto) {
        if (beiDiaoDto.getProductId() == null) {
            return warn("未选择报告");
        }
        Long userId = SecurityUtils.getUserId();
        beiDiaoDto.setUserId(userId);
        beiDiaoDto.setOrderNo("TQBD" + getId());
        beiDiaoDto.setAuthMethod("offline");
        beiDiaoDto.setAuthStatus("已线下授权");
        tbdm.insertBeiDiao(beiDiaoDto);
        Integer id = beiDiaoDto.getId();
        FeeResult feeResult = isqs.reportFee(id, beiDiaoDto.getProductId(), userId);
        if (!feeResult.isSuccess()) {
            return warn(feeResult.getMsg());
        }
        tbdm.insertBeiDiaoReport(new BeiDiaoReportBody(beiDiaoDto));
        return success(beiDiaoDto.getOrderNo());
    }

    @Anonymous
    @PostMapping("/elecAuth")
    public AjaxResult elecAuthAdd(@RequestBody BeiDiaoDto beiDiaoDto) {
        if (beiDiaoDto.getUserId() == null) {
            return warn("缺少参数");
        }
        beiDiaoDto.setOrderNo("TQBD" + getId());
        beiDiaoDto.setAuthMethod("elec");
        beiDiaoDto.setAuthStatus("未授权");
        tbdm.insertBeiDiao(beiDiaoDto);
        String info;
        try {
            info = tencentService.sendIdentityInfoUserInfo(new FacialVerification(beiDiaoDto));
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
        return success(info);
    }

    @RepeatSubmit
    @Transactional
    @PostMapping("/addLook")
    public AjaxResult addLook(@RequestBody BeiDiaoReportBody bdrb) {
        Long userId = SecurityUtils.getUserId();
        FeeResult feeResult = isqs.reportFee(bdrb.getReportId(), bdrb.getProductId(), userId);
        if (!feeResult.isSuccess()) {
            return warn(feeResult.getMsg());
        }
        tbdm.insertBeiDiaoReport(bdrb);
        return success();
    }

    @GetMapping("/rfv/{orderNo}")
    public AjaxResult requestFacialVerification(@PathVariable("orderNo") @NotBlank String orderNo) {
        BeiDiaoVo beiDiaoVo = tbdm.selectBeiDiao(orderNo);
        if (beiDiaoVo == null) {
            return warn("不存在订单");
        }
        try {
            String info = tencentService.sendIdentityInfoUserInfo(new FacialVerification(beiDiaoVo));
            return success(info);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**
     * 获取人脸核验结果
     *
     * @param fbrv
     * @throws Exception
     */
    @Anonymous
    @GetMapping(value = "/fvBack")
    public void fvBack(@Validated FaceBackResultVo fbrv) {
        try {
            tbds.handlerFaceAuth(fbrv);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param orderNo
     * @return
     */
    @GetMapping("/reportHead/{orderNo}")
    public AjaxResult reportHead(@PathVariable("orderNo") @NotBlank String orderNo) {
        BeiDiaoVo beiDiaoVo = tbdm.selectBeiDiao(orderNo);
        if (beiDiaoVo == null) {
            return warn("不存在的订单");
        }
        Report report;
        try {
            report = tbds.queryReportHead(beiDiaoVo);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
        return success(report);
    }

    /**
     * 已收费进行查询
     *
     * @param feeId
     */
    @GetMapping("/report/{feeId}")
    public AjaxResult report(@PathVariable("feeId") @NotNull Integer feeId) {
        Long userId = SecurityUtils.getUserId();
        SiyuCharge siyuCharge = scm.selectChargeByIdAndType(feeId, "beidiao");
        if (siyuCharge.getUserId().longValue() != userId) {
            return warn("非本人订单！");
        }
        return success(tbds.queryReport(siyuCharge));
    }

    /**
     * 收费进行查询
     *
     * @param beiDiaoId
     * @param productId
     */
    @Transactional
    @GetMapping("/feeQuery")
    public AjaxResult feeQuery(@NotNull Integer beiDiaoId, @NotNull Integer productId) {
        Long userId = SecurityUtils.getUserId();
        FeeResult feeResult = isqs.reportFee(beiDiaoId, productId, userId);
        if (!feeResult.isSuccess()) {
            return warn(feeResult.getMsg());
        }
        return success(tbds.queryReport(feeResult.getSiyuCharge()));
    }

    @GetMapping("/auth/{file}")
    public void authorizeFile(HttpServletResponse response, @PathVariable("file") @NotBlank String fileName) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", fileName));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + "/" + fileName;
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            File file = new File(downloadPath);
            long fileSize = file.length();
            response.setHeader("Content-Length", String.valueOf(fileSize));
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
